package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.domain.AppResponse;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.engine.protect.core.annotation.NoSignCrypto;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.EduSyncIrsEnum;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.eduSyncIrs.EduSyncIrsBatchVO;
import com.jwsoft.manager.common.vo.eduSyncIrs.EduSyncIrsKeyVO;
import com.jwsoft.manager.common.vo.eduSyncIrs.EduSyncIrsQueryVO;
import com.jwsoft.manager.common.vo.eduSyncIrs.EduSyncIrsVO;
import com.jwsoft.manager.core.dao.model.EduSyncIrs;
import com.jwsoft.manager.core.dao.service.EduSyncIrsService;
import com.jwsoft.manager.core.integration.EduSyncIrsIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
 * irs数据异步同步管理业务实现类
 *
 * @author chenzh
 * @since 2023-05-10
 */
@ApiService(funcCode = "eduSyncIrs", title = "irs数据异步同步管理")
public class EduSyncIrsIntegrationImpl implements EduSyncIrsIntegration {

    @Autowired
    public EduSyncIrsService eduSyncIrsService;
    @Autowired
    private EduHelper eduHelper;
    @Value("${system.config.irs.send.flag:false}")
    private Boolean irsSendFlag;
    @Autowired
    private CommonIntegration commonIntegration;
    @Autowired
    private DictHelper dictHelper;

    @Override
    @OpApi(funcCode = "eduSyncIrs0001", title = "irs数据异步同步管理分页查询", funcType = FuncTypeEnum.query,publicFlag = BoolEnum.TRUE)
    public PageInfo<EduSyncIrsVO> getList(EduSyncIrsQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        QueryWrapper<EduSyncIrs> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getNewFlag()),EduSyncIrs::getNewFlag,vo.getNewFlag())
                .eq(StringUtils.isNotBlank(vo.getSendFlag()),EduSyncIrs::getSendFlag,vo.getSendFlag())
                .eq(StringUtils.isNotBlank(vo.getIrsSendFlag()),EduSyncIrs::getIrsSendFlag,vo.getIrsSendFlag())
                .eq(StringUtils.isNotBlank(vo.getSyncStatus()),EduSyncIrs::getSyncStatus,vo.getSyncStatus())
                .eq(StringUtils.isNotBlank(vo.getIrsCode()),EduSyncIrs::getIrsCode,vo.getIrsCode())
                .eq(StringUtils.isNotBlank(vo.getIrsSyncId()),EduSyncIrs::getIrsSyncId,vo.getIrsSyncId())
                .eq(StringUtils.isNotBlank(vo.getDataId()),EduSyncIrs::getDataId,vo.getDataId())
                .eq(StringUtils.isNotBlank(vo.getDataType()),EduSyncIrs::getDataType,vo.getDataType())
                .eq(StringUtils.isNotBlank(vo.getStudentEnrollPreId()),EduSyncIrs::getStudentEnrollPreId,vo.getStudentEnrollPreId())
                .eq(StringUtils.isNotBlank(vo.getSyncType()),EduSyncIrs::getSyncType,vo.getSyncType())
                .eq(vo.getYear()!=null,EduSyncIrs::getYear,vo.getYear())
                .orderByDesc(EduSyncIrs::getReqTime);
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<EduSyncIrs> list = eduSyncIrsService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSyncIrs> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSyncIrsVO> resultList = Convert.toList(EduSyncIrsVO.class, pageInfo.getList());
        // 转义数据字典值
         dictHelper.valueToName(resultList, Arrays.asList(EduSyncIrsEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0011", title = "查询东阳教育irs转发平台数据分页查询", funcType = FuncTypeEnum.query,publicFlag = BoolEnum.TRUE)
    public PageInfo<EduSyncIrsVO> getListIrs(EduSyncIrsQueryVO vo) {
        //调用发送接口
        String areaCode=SessionUtil.getAreaCode();
        if(StringUtils.isBlank(areaCode)){
            areaCode=eduHelper.thisAreaCode();
        }
        CommonVO commonSendVO = new CommonVO();
        commonSendVO.setParamKey("IRS_LOCAL0005");
        commonSendVO.setAreaCode(areaCode);
        String sendUrl = commonIntegration.getValueByKeyAndArea(commonSendVO);
        if (StringUtils.isBlank(sendUrl)) {
            throw new AppException("请先在系统参数表中设置IRS_LOCAL0005（查询本地irs平台详情数据）");
        }
        try {
            HttpRequest request = HttpRequest.post(sendUrl).body(JSON.toJSONString(vo)).timeout(2000)
                    .header("appId", "20230008"); // 添加自定义请求头
            // 发送请求
            HttpResponse response = request.execute();
            String body= response.body();
            AppResponse<PageInfo<EduSyncIrsVO>> appResponse=JSON.parseObject(body,AppResponse.class);
            if(appResponse.getCode()!=0){
                throw new AppException("东阳教育irs转发平台失败："+appResponse.getMessage());
            }
            return JSON.parseObject(JSON.toJSONString(appResponse.getResult()),PageInfo.class);
        }catch (AppException e){
            throw e;
        }catch (Exception e){
            throw new AppException("调用异常：网络不通",e);
        }
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0002", title = "irs数据异步同步管理根据主键查询详情", funcType = FuncTypeEnum.query,publicFlag = BoolEnum.TRUE)
    public EduSyncIrsVO getById(EduSyncIrsKeyVO vo) {

        EduSyncIrs entity = eduSyncIrsService.getById(vo.getIrsSyncId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSyncIrsVO result = Convert.convert(EduSyncIrsVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduSyncIrs0003", title = "irs数据异步同步管理保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSyncIrsVO vo) {
        if(StringUtils.isBlank(vo.getDataId())){
            throw new AppException("对应数据id不能为空");
        }
        if(StringUtils.isBlank(vo.getDataType())){
            throw new AppException("对应数据类型不能为空");
        }
        if(StringUtils.isBlank(vo.getSyncType())){
            throw new AppException("同步类型不能为空");
        }
        if(StringUtils.isBlank(vo.getIrsCode())){
            throw new AppException("irs接口编号不能为空");
        }
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0004", title = "irs数据异步同步管理新增", funcType = FuncTypeEnum.insert,publicFlag = BoolEnum.TRUE,savelog = false)
    @SaveOplog(
            operationType = "eduSyncIrs0004",
            operationName = "irs数据异步同步管理新增",
            dataType = "irsSyncId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncIrsVO add(EduSyncIrsVO vo) {
        //保存前校验
        checkSave(vo);
        Integer year=vo.getYear();
        if(year==null&&!irsSendFlag){
            year=eduHelper.thisYear();
        }
        if(!irsSendFlag) {
            QueryWrapper<EduSyncIrs> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduSyncIrs::getYear, year)
                    .eq(EduSyncIrs::getDataType, vo.getDataType())
                    .eq(EduSyncIrs::getSyncStatus, "0")
                    .eq(EduSyncIrs::getDataId, vo.getDataId()).eq(EduSyncIrs::getSyncType, vo.getSyncType())
                    .eq(StringUtils.isNotBlank(vo.getStudentEnrollPreId()), EduSyncIrs::getStudentEnrollPreId, vo.getStudentEnrollPreId())
                    .eq(EduSyncIrs::getNewFlag, BoolEnum.TRUE.getType()).orderByDesc(EduSyncIrs::getReqTime);
            if (eduSyncIrsService.count(queryWrapper) > 0) {
                throw new AppException("之前已发送请求，请耐心等待结果");
            }
        }
        UpdateWrapper<EduSyncIrs> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(EduSyncIrs::getNewFlag, BoolEnum.FALSE.getType()).eq(EduSyncIrs::getYear, year)
                .eq(EduSyncIrs::getDataType, vo.getDataType())
                .eq(EduSyncIrs::getDataId, vo.getDataId()).eq(EduSyncIrs::getSyncType, vo.getSyncType())
                .eq(StringUtils.isNotBlank(vo.getStudentEnrollPreId()), EduSyncIrs::getStudentEnrollPreId, vo.getStudentEnrollPreId())
                .eq(EduSyncIrs::getNewFlag, BoolEnum.TRUE.getType());
        eduSyncIrsService.update(updateWrapper);
        //保存数据
        EduSyncIrs entity = Convert.convert(EduSyncIrs.class, vo);

        entity.setSyncStatus("0");
        entity.setIrsSendFlag("0");
        entity.setReqTime(new Date());
        if (irsSendFlag) {
            //irs 转发平台
            if(StringUtils.isBlank(entity.getIrsSyncId())){
                throw new AppException("同步id不能为空");
            }
            entity.setSendFlag("1");
            entity.setIrsSendTime(new Date());
        } else {
            entity.setIrsSyncId(IdUtil.simpleUUID());
            entity.setSendFlag("0");
        }
        entity.setNewFlag("1");
        eduSyncIrsService.saveOrUpdate(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setIrsSyncId(entity.getIrsSyncId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0007", title = "irs数据异步同步管理新增批量", funcType = FuncTypeEnum.insert,publicFlag = BoolEnum.TRUE,savelog = false)
    public void addBatch(EduSyncIrsBatchVO vo) {
        if(CollectionUtils.isEmpty(vo.getList())){
            return;
        }
        for(EduSyncIrsVO irsVO:vo.getList()){
            this.add(irsVO);
        }
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0005", title = "irs数据异步同步管理修改", funcType = FuncTypeEnum.update,publicFlag = BoolEnum.TRUE)
    @SaveOplog(
            operationType = "eduSyncIrs0005",
            operationName = "irs数据异步同步管理修改",
            dataType = "irsSyncId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncIrsVO edit(EduSyncIrsVO vo) {
        if (ObjectUtils.isEmpty(vo.getIrsSyncId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSyncIrs oldEntity = eduSyncIrsService.getById(vo.getIrsSyncId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSyncIrs entity = Convert.convert(EduSyncIrs.class, vo);
        eduSyncIrsService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0012", title = "东阳教育转发irs平台数据异步同步管理修改", funcType = FuncTypeEnum.update)
    public EduSyncIrsVO editIrs(EduSyncIrsVO vo) {
        //调用发送接口
        String areaCode=SessionUtil.getAreaCode();
        if(StringUtils.isBlank(areaCode)){
            areaCode=eduHelper.thisAreaCode();
        }
        CommonVO commonSendVO = new CommonVO();
        commonSendVO.setParamKey("IRS_LOCAL0006");
        commonSendVO.setAreaCode(areaCode);
        String sendUrl = commonIntegration.getValueByKeyAndArea(commonSendVO);
        if (StringUtils.isBlank(sendUrl)) {
            throw new AppException("请先在系统参数表中设置IRS_LOCAL0006（本地irs平台发送数据修改）");
        }
        try {
            HttpRequest request = HttpRequest.post(sendUrl).body(JSON.toJSONString(vo)).timeout(2000)
                    .header("appId", "20230008"); // 添加自定义请求头
            // 发送请求
            HttpResponse response = request.execute();
            String body= response.body();
            AppResponse<EduSyncIrsVO> appResponse=JSON.parseObject(body,AppResponse.class);
            if(appResponse.getCode()!=0){
                throw new AppException("东阳教育irs转发平台失败："+appResponse.getMessage());
            }
            return JSON.parseObject(JSON.toJSONString(appResponse.getResult()),EduSyncIrsVO.class);
        }catch (AppException e){
            throw e;
        }catch (Exception e){
            throw new AppException("调用异常：网络不通",e);
        }
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0006", title = "irs数据异步同步管理根据主键删除", funcType = FuncTypeEnum.delete,publicFlag = BoolEnum.TRUE)
    @SaveOplog(
            operationType = "eduSyncIrs0006",
            operationName = "irs数据异步同步管理删除",
            dataType = "irsSyncId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSyncIrsKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getIrsSyncId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSyncIrs entity = eduSyncIrsService.getById(vo.getIrsSyncId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSyncIrsService.removeById(vo.getIrsSyncId());
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0013", title = "东阳教育转发irs平台数据异步同步管理删除", funcType = FuncTypeEnum.delete)
    public void delIrs(EduSyncIrsKeyVO vo) {
        //调用发送接口
        String areaCode=SessionUtil.getAreaCode();
        if(StringUtils.isBlank(areaCode)){
            areaCode=eduHelper.thisAreaCode();
        }
        CommonVO commonSendVO = new CommonVO();
        commonSendVO.setParamKey("IRS_LOCAL0007");
        commonSendVO.setAreaCode(areaCode);
        String sendUrl = commonIntegration.getValueByKeyAndArea(commonSendVO);
        if (StringUtils.isBlank(sendUrl)) {
            throw new AppException("请先在系统参数表中设置IRS_LOCAL0007（本地irs平台发送数据删除）");
        }
        try {
            HttpRequest request = HttpRequest.post(sendUrl).body(JSON.toJSONString(vo)).timeout(2000)
                    .header("appId", "20230008"); // 添加自定义请求头
            // 发送请求
            HttpResponse response = request.execute();
            String body= response.body();
            AppResponse<EduSyncIrsVO> appResponse=JSON.parseObject(body,AppResponse.class);
            if(appResponse.getCode()!=0){
                throw new AppException("东阳教育irs转发平台失败："+appResponse.getMessage());
            }
        }catch (AppException e){
            throw e;
        }catch (Exception e){
            throw new AppException("调用异常：网络不通",e);
        }
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0008", title = "重置发送东阳教育irs转发平台错误数据", funcType = FuncTypeEnum.edit,savelog = false)
    public void resetSendFlag(AreaControlVO vo) {
        UpdateWrapper<EduSyncIrs> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().set(EduSyncIrs::getSendFlag,BoolEnum.FALSE.getType()).set(EduSyncIrs::getSendErrorCnt,0)
                .eq(EduSyncIrs::getSendFlag,"2")
                .eq(StringUtils.isNotBlank(vo.getIrsCode()),EduSyncIrs::getIrsCode,vo.getIrsCode())
                .eq(StringUtils.isNotBlank(vo.getSyncType()),EduSyncIrs::getSyncType,vo.getSyncType());
        eduSyncIrsService.update(updateWrapper);
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0009", title = "重置同步东阳教育irs转发平台错误数据", funcType = FuncTypeEnum.edit,savelog = false)
    public void resetSyncFlag(AreaControlVO vo) {
        UpdateWrapper<EduSyncIrs> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().set(EduSyncIrs::getSyncStatus,BoolEnum.FALSE.getType()).set(EduSyncIrs::getSyncErrorCnt,0)
                .eq(EduSyncIrs::getSyncStatus,"2")
                .eq(StringUtils.isNotBlank(vo.getIrsCode()),EduSyncIrs::getIrsCode,vo.getIrsCode())
                .eq(StringUtils.isNotBlank(vo.getSyncType()),EduSyncIrs::getSyncType,vo.getSyncType());
        eduSyncIrsService.update(updateWrapper);
    }

    @Override
    @OpApi(funcCode = "eduSyncIrs0010", title = "获取东阳教育irs转发平台单条的详情信息", funcType = FuncTypeEnum.query,publicFlag = BoolEnum.TRUE)
    public EduSyncIrsVO getByIdIrs(EduSyncIrsKeyVO vo) {
        //调用发送接口
        String areaCode=SessionUtil.getAreaCode();
        if(StringUtils.isBlank(areaCode)){
            areaCode=eduHelper.thisAreaCode();
        }
        CommonVO commonSendVO = new CommonVO();
        commonSendVO.setParamKey("IRS_LOCAL0003");
        commonSendVO.setAreaCode(areaCode);
        String sendUrl = commonIntegration.getValueByKeyAndArea(commonSendVO);
        if (StringUtils.isBlank(sendUrl)) {
            throw new AppException("请先在系统参数表中设置IRS_LOCAL0003（查询本地irs平台详情数据）");
        }
        try {
            HttpRequest request = HttpRequest.post(sendUrl).body(JSON.toJSONString(vo)).timeout(2000)
                    .header("appId", "20230008"); // 添加自定义请求头
            // 发送请求
            HttpResponse response = request.execute();
            String body= response.body();
            AppResponse<EduSyncIrsVO> appResponse=JSON.parseObject(body,AppResponse.class);
            if(appResponse.getCode()!=0){
                throw new AppException(appResponse.getMessage());
            }
            return JSON.parseObject(JSON.toJSONString(appResponse.getResult()),EduSyncIrsVO.class);
        }catch (AppException e){
            throw e;
        }catch (Exception e){
            throw new AppException("调用异常：网络不通"+e.getMessage());
        }
    }
}
